package com.test40_JDBC;

import com.test40_JDBC.util.JDBCUtil;
import org.junit.Test;

import java.sql.*;

/**
 * JDBC元数据(Meta Data)
 */
public class Demo06_MetaData {

    /**
     * 获取数据库的元数据信息
     */
    @Test
    public void test1() throws Exception {
        Connection conn = JDBCUtil.getConnection();
        DatabaseMetaData metaData = conn.getMetaData();
        System.out.println("【数据库的主版本号】" + metaData.getDatabaseMajorVersion());
        System.out.println("【数据库的子版本号】" + metaData.getDatabaseMinorVersion());
        System.out.println("【数据库的产品名称】" + metaData.getDatabaseProductName());
        ResultSet resultSet = metaData.getPrimaryKeys(null, "root", "user");
        if (resultSet.next()) {
            System.out.println("【catalog】" + resultSet.getObject(1));
            System.out.println("【表名称】" + resultSet.getObject(3));
            System.out.println("【主键字段】" + resultSet.getObject(4));
        }
        JDBCUtil.closeConnection(conn);
    }

    /**
     * 获取结果集的元数据信息
     */
    @Test
    public void test2() throws Exception {
        Connection conn = JDBCUtil.getConnection();
        String sql = "SELECT uid,name,age,birthday,salary,note FROM user WHERE uid=?";
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        preparedStatement.setObject(1, 36);
        ResultSet rs = preparedStatement.executeQuery();
        ResultSetMetaData metaData = rs.getMetaData();
        System.out.println("获取返回数据的列数：" + metaData.getColumnCount());
        for (int x = 1; x <= metaData.getColumnCount(); x++) {
            System.out.printf("列名称：%s、列类型：%s、列常量值：%s\n",
                    metaData.getColumnName(x), metaData.getColumnTypeName(x), metaData.getColumnType(x));
        }
        JDBCUtil.closeConnection(conn);
    }
}
